import Vuex from 'vuex';
import Vue from "vue";
import router from '../router';
import eventBus from '../data/websocket'

Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    user: {
      id: Number,
      nickname: String,
      avatar: String,
      token: String
    },
    chatList: [
      {
        id: Number,
        nickname: String,
        avatar: String,
        lastMessage: String,
        lastDate: String
      }
    ]
  },
  mutations: {
    initData(state) {
      state.user = getObject(USER);
      state.chatList = getArray(CHAT_LIST);
      if (state.user === {}) {
        router.push({ path: '/login'});
      } else {
        let obj = {}
        obj.id = 1
        obj.token = state.user.token
        eventBus.$emit('Send', obj)
      }
    },
    setUser(state, user) {
      state.user = user
    }
  },
  actions: {
    initData: ({ commit }) => commit('initData')
  }
});

const USER = "user";

const CHAT_LIST = "chat_list";

const MESSAGE = "message";

function getObject(key) {
  let str = localStorage.getItem(key);
  if (str == null) {
    return {};
  } else {
    return JSON.parse(str);
  }
}

function getArray(key) {
  let str = localStorage.getItem(key);
  if (str == null) {
    return [];
  } else {
    return JSON.parse(str);
  }
}

function setData(key, value) {
  localStorage.setItem(key, value)
}

export default store;
